/* eslint-disable react-hooks/exhaustive-deps */
/*
{
  car001: {name: '本田', price: 100},
  car002: {name: '宝马', price: 200},
  car003: {name: '奔驰', price: 240}
}
*/

import { createContext, memo, useCallback, useContext, useState } from 'react'

const CarsContext = createContext()

const Car = ({id, car, incr, decr}) => {
  console.log('Car', id)
  const {cars} = useContext(CarsContext)
  return <div>
    <p>名称：{car.name}</p>
    <p>价格：{car.price}</p>
    <button className='btn btn-primary'
      onClick={() => incr(cars)(id)}
    >增加</button>
    <button className='btn btn-primary'
      onClick={() => decr(cars)(id)}
    >减少</button>
  </div>
}

const Cars = () => {
  console.log('Cars')
  const{cars, incr, decr} = useContext(CarsContext)
  return <div>
    {Object
        .keys(cars)
        .map((id) => <Car
          id={id}
          key={id}
          car={cars[id]}
          incr={incr}
          decr={decr}
         />)
    }
  </div>
}

const ProductList = memo(() => {
  console.log('ProductList')
  return (
    <>
      <h3>汽车：</h3>
      <Cars />
    </>
  )
})

const CarsDemo = () => {
  console.log('CarsDemo')
  const [state, setState] = useState({
    car001: { name: '本田', price: 100 },
    car002: { name: '宝马', price: 200 },
    car003: { name: '奔驰', price: 240 },
  })
  const incrPrice = useCallback((state) => (carId) => {
    setState({
      ...state,
      [carId]: {
        ...state[carId],
        price: state[carId].price + 1,
      },
    })
  }, [setState])
  const decrPrice = useCallback((state) => (carId) => {
    setState({
      ...state,
      [carId]: {
        ...state[carId],
        price: state[carId].price - 1,
      },
    })
  }, [setState])
  return (
    <CarsContext.Provider value={{
      cars: state, incr: incrPrice, decr: decrPrice
    }}>
      <h2>产品展厅</h2>
      <ProductList />
    </CarsContext.Provider>
  )
}

export default CarsDemo
